﻿$(document).ready(function () {
    //alert("hello");
    $("#txtTag").keypress(function (event) {
        //alert("txtTag onchange event");
        if (event.which == 32) {
            $("#taglist").append("<div class='tag'><div class='tagText'>" + $("#txtTag").val() + "</div><div class='removeTag'></div></div>");
            $(this).val("");
        }
    });
        
        $("#txtTag").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Tag/GetTags",
                    type: "POST",
                    dataType: "json",
                    data: JSON.stringify({ keyword: request.term }),
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        var taglist =$.map(JSON.parse( data.replace(/'/g,'"')), function (t) {
                            //alert(item);
                            return { label: t.TagName,value:t.TagName };
                        });
                        response(taglist);                    
                    }
                });
            },
            minLength: 1,
            select: function (event, ui) {

            }
        });

    $("form").submit(function () {
        var tags = [];
        $(".tagText").each(function(){
            //alert($(this).text()+"!");
            tags.push($(this).text());
        });
        //alert($("#PostContent").val());

        tinyMCE.triggerSave();

        var askModel = {
            Title: $("#Title").val(),
            Content: $("#Content").val(),
            Tags: tags
        };

        //alert($("#Content").length);

        $.ajax({
            type: "post",
            url: $(this).attr("action"),
            dataType: 'json',
            contentType:'application/json; charset=utf-8',
            data: JSON.stringify(
                askModel    
            ),
            success: function (result) {
                //alert("OK! " + result);
                window.location.replace("Details?questionID=" + result);
            },
            error: function (result) {
                alert('error')
            }
        });
        return false;
    });    
});